package com.pine.dcts.taskScheduling.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pine.app.module.security.core.common.SpringContextUtils;
import com.pine.dcts.common.TaskType;
import com.pine.dcts.core.IPluginConfigHandler;
import com.pine.dcts.model.JobVO;
import com.pine.dcts.service.DefaultTaskRunnerCallback;
import com.pine.dcts.service.JobConfigBuilder;
import com.pine.dcts.service.JobService;
import com.pine.dcts.task.DataxTask;
import com.pine.dcts.task.DataxTaskRunner;
import com.pine.dcts.task.status.DefaultTaskStatusUpdator;
import com.pine.dcts.taskScheduling.scheduler.DynamicScheduler;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Collection;

/**
 * 可以并行执行datax任务
 */
@Setter
@Getter
@Slf4j
public class DataxJob extends AbstractJob {

    private static final JobService JOB_SERVICE = SpringContextUtils.getBean(JobService.class);
    private static final Collection<IPluginConfigHandler> pluginConfigHandlers = SpringContextUtils.getBeanMap(IPluginConfigHandler.class).values();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        JSONObject jsonObject = JSON.parseObject(jobDataMap.getString(DynamicScheduler.SCHEDULER_NAME));
        JobVO jobVO = JOB_SERVICE.getJobVOById(jsonObject.getInteger("id"));
        if (jobVO == null) {
            throw new JobExecutionException("当前job【" + jsonObject.getString("id") + "】不存在");
        }
        DataxTask taskMeta = new DataxTask(String.valueOf(jobVO.getId()), jobVO.getName(), JobConfigBuilder.buildConfig(jobVO), TaskType.SCHEDULE, null, jobVO);
        new DataxTaskRunner(taskMeta,
                new DefaultTaskRunnerCallback(taskMeta, new DefaultTaskStatusUpdator())).execute();
    }
}
